package com.jinlejia.erp.ui.house;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListInterface;
import com.freedom.yefeng.yfrecyclerview.YfListRecyclerView;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.RentAdapter;
import com.jinlejia.erp.adapter.SellingAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.ui.common.CommonDeleteDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;


public class InterestFragment extends Fragment implements YfLoadMoreListener {

    //(<1>兴趣房源、<2>兴趣小区房源)
    private String houseType;
    //求租、求购(布局标识)
    private String customerType;
    private String customerCode;
    RentAdapter rentAdapter;
    SellingAdapter sellingAdapter;

    private int page = 1;
    private boolean mLoadingLock = false;
    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();
    private JSONObject jsonObject = new JSONObject();
    String DELICON = "";

    public InterestFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static InterestFragment newInstance(String houseType, String customerType, String code) {
        InterestFragment fragment = new InterestFragment();
        Bundle args = new Bundle();
        args.putString("houseType", houseType);
        args.putString("customerType", customerType);
        args.putString("customerCode", code);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            customerType = getArguments().getString("customerType");
            houseType = getArguments().getString("houseType");
            customerCode = getArguments().getString("customerCode");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_interest, container, false);
        YfListRecyclerView recyclerView = (YfListRecyclerView) view.findViewById(R.id.yf_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setHasFixedSize(true);
        recyclerView.enableAutoLoadMore(this);

        if (houseType.equals("1")) {
            //兴趣房源显示删除按钮
            DELICON = "DEL";
        }

        if (customerType.equals("rent")) {
            ArrayList<Map<String, Object>> list = new ArrayList();
            rentAdapter = new RentAdapter(list, DELICON);
            recyclerView.setAdapter(rentAdapter);
            jsonObject.put("type", 0);
        } else {
            ArrayList<Map<String, Object>> list1 = new ArrayList<>();
            sellingAdapter = new SellingAdapter(list1, DELICON);
            recyclerView.setAdapter(sellingAdapter);
            jsonObject.put("type", 1);
        }
//        getHouse();
        recyclerView.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        if (null != rentAdapter) {
            rentAdapter.setOnItemClickListener(new YfListInterface.OnItemClickListener() {
                @Override
                public void onItemClick(View view, Object o) {
                    Map<String, Object> map = (Map<String, Object>) o;
                    Intent intent = new Intent(getActivity(), HouseDetailActivity.class);
                    intent.putExtra("type", "rent");
                    if (map.containsKey("rsCode"))
                        intent.putExtra("code", map.get("rsCode").toString());
                    if (map.containsKey("rscode"))
                        intent.putExtra("code", map.get("rscode").toString());
                    intent.putExtra("name", map.get("estate").toString());
                    startActivity(intent);
                }
            });
            //取消租赁兴趣
            rentAdapter.setOnDeleteListener(new RentAdapter.OnDeleteListener() {
                @Override
                public void onDelete(final int position, final String rscode, String name) {

                    CommonDeleteDialog dialog = new CommonDeleteDialog(getActivity(), "删除", "确定删除" + name + "?");
                    dialog.show();
                    dialog.setConfirmListener(new CommonDeleteDialog.OnConfirmListener() {
                        @Override
                        public void confirm() {
                            delEnjoy(customerCode, rscode, position);
                        }
                    });
                }
            });
        }
        if (null != sellingAdapter) {
            sellingAdapter.setOnItemClickListener(new YfListInterface.OnItemClickListener() {
                @Override
                public void onItemClick(View view, Object o) {
                    Map<String, Object> map = (Map<String, Object>) o;
//                    System.out.println(map.entrySet());
                    Intent intent = new Intent(getActivity(), HouseDetailActivity.class);
                    intent.putExtra("type", "shs");
                    if (map.containsKey("rsCode"))
                        intent.putExtra("code", map.get("rsCode").toString());
                    if (map.containsKey("rscode"))
                        intent.putExtra("code", map.get("rscode").toString());
                    intent.putExtra("name", map.get("estate").toString());
                    startActivity(intent);
                }
            });
            //取消买卖兴趣
            sellingAdapter.setOnDeleteListener(new SellingAdapter.OnDeleteListener() {
                @Override
                public void onDelete(final int position, final String rscode, String name) {

                    CommonDeleteDialog dialog = new CommonDeleteDialog(getActivity(), "删除", "确定删除" + name + "?");
                    dialog.show();
                    dialog.setConfirmListener(new CommonDeleteDialog.OnConfirmListener() {
                        @Override
                        public void confirm() {
                            delEnjoy(customerCode, rscode, position);
                        }
                    });
                }
            });
        }

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getHouse();
    }

    /*兴趣房源*/
    private void getHouse() {
        String url;
        if (houseType.equals("1")) {
            if (customerType.equals("rent")) {
                url = ApiConfig.ENJOY_RENT_HOUSE;
            }else {
                url = ApiConfig.ENJOY_SHS_HOUSE;
            }
        } else {
            if (customerType.equals("rent")) {
                url = ApiConfig.ENJOY_RENT_ESTATE;
            }else{
                url = ApiConfig.ENJOY_SHS_ESTATE;
            }
        }
        mLoadingLock = true;
        jsonObject.put("pageSize", 20);
        jsonObject.put("pageIndex", page);
        jsonObject.put("csCode", customerCode);
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (customerType.equals("rent")) {
                            if (DataFilter.filter(getActivity(), response, rentAdapter)) {
                                JSONArray data = JSON.parseArray(response.get("data").toString());
                                //数据列表
                                ArrayList<Map<String, Object>> list = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                                if (page == 1) {
                                    rentAdapter.setData(list);
                                } else {
                                    rentAdapter.addData(list);
                                }
                            } else if (response.get("code").toString().equals("303")) {
                                //没有更多
                                page--;
                            }
                            if (rentAdapter.getFooters().size() > 0)
                                rentAdapter.removeAllFooters();
                        } else {
                            if (DataFilter.filter(getActivity(), response, sellingAdapter)) {
                                JSONArray data = JSON.parseArray(response.get("data").toString());
                                //数据列表
                                ArrayList<Map<String, Object>> list = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                                if (page == 1) {
                                    sellingAdapter.setData(list);
                                } else {
                                    sellingAdapter.addData(list);
                                }
                            } else if (response.get("code").toString().equals("303")) {
                                //没有更多
                                page--;
                            }
                            if (sellingAdapter.getFooters().size() > 0)
                                sellingAdapter.removeAllFooters();
                        }

                        mLoadingLock = false;
                    }
                });
    }


    @Override
    public void loadMore() {
        if (customerType.equals("rent")) {
            if (rentAdapter.getData().size() % 20 == 0) {
                if (mLoadingLock) {
                    return;
                }
                mLoadingLock = true;
                page++;
                rentAdapter.addFooter("loading");

                getHouse();
            }
        } else {
            if (sellingAdapter.getData().size() % 20 == 0) {
                if (mLoadingLock) {
                    return;
                }
                mLoadingLock = true;
                page++;
                sellingAdapter.addFooter("loading");

                getHouse();
            }
        }
    }

    /**
     * 删除兴趣房源
     *
     * @param csCode
     * @param rsCode
     */
    private void delEnjoy(String csCode, String rsCode, final int position) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rsCode", rsCode);
        jsonObject.put("csCode", csCode);
        String url;
        if (customerType.equals("shs")|| customerType.equals("sale")) {
            url = ApiConfig.REMOVE_SHS_ENJOY_HOUSE;
        } else {
            url = ApiConfig.REMOVE_RENT_ENJOY_HOUSE;
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response)) {

                            if (customerType.equals("shs")|| customerType.equals("sale") ) {
                                sellingAdapter.notifyItemRemoved(position);
                                sellingAdapter.mData.remove(position);
                                sellingAdapter.notifyItemRangeChanged(position, sellingAdapter.mData.size() - position);
                            } else {
                                rentAdapter.notifyItemRemoved(position);
                                rentAdapter.mData.remove(position);
                                rentAdapter.notifyItemRangeChanged(position, rentAdapter.mData.size() - position);
                            }

                        }
                    }
                });
    }
}
